#include "Timer.h"

/*********************************************************/
void Timer::run()
{
	if ( persistant ) {
		mutex.lock();
		while ( !quit ) {
			mutex.unlock();
			for ( unsigned int i = 0; i<timeout; i++ ) usleep(1);
			event->set();
			mutex.lock();
		}
		mutex.unlock();
	} else {
		for ( unsigned int i = 0; i<timeout; i++ ) {
			usleep(1);
		
			mutex.lock();
			if ( quit ) return;
			mutex.unlock();
		}

		event->set();
	}
}
/*********************************************************/
void Timer::stop()
{
	mutex.lock();
	quit = true;
	mutex.unlock();
}
/*********************************************************/
Timer::Timer(std::string event, unsigned int timeout, bool persistant)
{
	// Set the internal variables
	Timer::event = Event::Instance(event);
	Timer::timeout = timeout;
	Timer::persistant = persistant;
	quit = false;

	// Start the thread
	if ( lThread.isRunning() ) {
		throw(std::logic_error("Timer thread allready running!"));
	} else {
		lThread.start((*this));
	}
}
/*********************************************************/
Timer::~Timer()
{
	stop();
	lThread.join();
}

